package com.qing.springcloud.handler;

import com.qing.springcloud.manger.UserChannelManager;
import com.qing.springcloud.model.ChatMessage;
import com.qing.springcloud.model.MsgType;
import com.qing.springcloud.model.UserStatus;
import com.qing.springcloud.service.MessageService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.qing.springcloud.model.MsgType.*;

@Component
@ChannelHandler.Sharable
public class WebSocketHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserChannelManager channelManager;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
        if (frame instanceof TextWebSocketFrame) {
            String text = ((TextWebSocketFrame) frame).text();
            ChatMessage chatMessage = ChatMessage.fromJson(text);

            // 处理不同类型的消息
            switch (chatMessage.getMsgType()) {
                case PRIVATE:
                    handlePrivateMessage(ctx, chatMessage);
                    break;
                case GROUP:
                    handleGroupMessage(ctx, chatMessage);
                    break;
                case ACK:
                    handleAckMessage(ctx, chatMessage);
                    break;
                case HEARTBEAT:
                    handleHeartbeat(ctx, chatMessage);
                    break;
                case STATUS:
                    handleStatusUpdate(ctx, chatMessage);
                    break;
            }
        }
    }

    private void handlePrivateMessage(ChannelHandlerContext ctx, ChatMessage msg) {
        // 验证用户身份
        Long userId = channelManager.getUserId(ctx.channel());
        if (userId == null || !userId.equals(msg.getSenderId())) {
            ctx.close();
            return;
        }

        // 转发消息给接收方
        messageService.sendPrivateMessage(msg);
    }

    private void handleGroupMessage(ChannelHandlerContext ctx, ChatMessage msg) {
        // 验证用户身份
        Long userId = channelManager.getUserId(ctx.channel());
        if (userId == null || !userId.equals(msg.getSenderId())) {
            ctx.close();
            return;
        }

        // 转发消息给群组
        messageService.sendGroupMessage(msg);
    }

    private void handleAckMessage(ChannelHandlerContext ctx, ChatMessage msg) {
        // 处理消息确认
        messageService.markMessageRead(msg);
    }

    private void handleHeartbeat(ChannelHandlerContext ctx, ChatMessage msg) {
        ChatMessage chatMessage=new ChatMessage();
        chatMessage.setMsgType(MsgType.HEARTBEAT);
        chatMessage.setSenderId(msg.getSenderId());
        chatMessage.setContent("HEARTBEAT_ACK");
        chatMessage.setExtra("SERVER");
        // 响应心跳
        ctx.writeAndFlush(new TextWebSocketFrame(chatMessage.toJson()));
    }

    private void handleStatusUpdate(ChannelHandlerContext ctx, ChatMessage msg) {
        // 更新用户状态
        UserStatus status = UserStatus.valueOf(msg.getContent());
        channelManager.updateUserStatus(msg.getSenderId(), status);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        // 新连接建立
        channelManager.addChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        // 连接断开
        Long userId = channelManager.getUserId(ctx.channel());
        if (userId != null) {
            channelManager.removeChannel(userId);
            channelManager.updateUserStatus(userId, UserStatus.OFFLINE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}